package com.vzoom.logdesensitization.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.vzoom.logdesensitization.DesensitizationStrategy;
import com.vzoom.logdesensitization.config.DesensitizationConfig;
import com.vzoom.logdesensitization.config.DesensitizationStrategyHolder;
import com.vzoom.logdesensitization.util.MapTransforms;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class XmlStrDesensitizationStringSerializer extends JsonSerializer<String> implements InitializingBean {

    private static Map<String, String> xmlStr = new HashMap<>();

    private static Map<String, DesensitizationStrategy> strategyMap;

    @Autowired
    private DesensitizationConfig desensitizationConfig;

    @Autowired
    private DesensitizationStrategyHolder desensitizationStrategyHolder;

    @Override
    public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            jsonGenerator.writeNull();
        } else {
            JsonStreamContext outputContext = jsonGenerator.getOutputContext();
            String currentName = outputContext.getCurrentName();
            String strategy = null;
            if (xmlStr.containsKey(currentName)) {
                strategy = xmlStr.get(currentName);
            }
            if (strategy != null) {
                DesensitizationStrategy desensitizationStrategy = strategyMap.get(strategy);
                jsonGenerator.writeString(desensitizationStrategy.desensitization(value));
            } else {
                jsonGenerator.writeString(value);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        MapTransforms.reverseMap(desensitizationConfig.getXmlStr(), xmlStr);
        strategyMap = desensitizationStrategyHolder.getStrategyMap();
    }
}
